import styled from 'styled-components';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import { localSharingGetSharedObject } from '../../services';

import { SharedPanel } from './shared-panel';
import { SharingPanel } from './/sharing-panel';

export interface SharePanelProps {
    style?: CSSProperties;
    objectType: string;
    referId: string;
    init?: { name?: string, icon?: string, description?: string };
    getDownload: (objectType: string, referId: string, identifier: string) => Promise<string | null>;
}

export const SharePanel: React.FC<SharePanelProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [identifier, setIdentifier] = useState<string | null>(null);

    const [localVersion, setLocalVersion] = useState<string | null>(null);

    const [lastVersion, setLastVersion] = useState<string | null>(null);

    const refresh = async (objectType: string, referId: string) => {
        let obj = await localSharingGetSharedObject(objectType, referId);
        if (obj !== null) {
            setIdentifier(obj.sharedObjectIdentifier);
            setLocalVersion(obj.localVersion);
            setLastVersion(obj.lastVersion);
        } else {
            setIdentifier(null);
            setLocalVersion(null);
            setLastVersion(null);
        }
    };
    useEffect(() => {
        refresh(props.objectType, props.referId);
    }, [props.objectType, props.referId]);

    const onFinish = useCallback(async () => {
        refresh(props.objectType, props.referId);
    }, [props.objectType, props.referId]);

    if (!identifier) {
        //没有分享过
        return (
            <SharingPanel {...props} onFinish={onFinish}></SharingPanel>
        );
    }

    return (
        <SharedPanel  {...props}
            identifier={identifier}
            lastVersion={lastVersion}
            localVersion={localVersion} onFinish={onFinish}></SharedPanel>
    );
}

const Container = styled.div`
    width: 100%;
    height: 100%;
    padding: 6px 6px;
    display: flex;
    gap: 10px;
`;
